﻿#include <iostream>
#include <curl/curl.h>
#include <thread>
#include "EnvEncode.cpp"
#include "include/nlohmann/json.hpp"
#include "BilMsg.h"

static bool workingState = false;       // 全局工作状态管理
static BilMsg::MsgManager msgManager{}; // 全局弹幕消息管理器

// 写入回调
static size_t writeCallback(void* contents, size_t size, size_t nmemb, std::string* userp)
{
    ((std::string*)userp)->append((char*)contents, size * nmemb);
    return size * nmemb;
}

// 读取弹幕数据
static void readBarrage(const std::string& text)
{
    using json = nlohmann::json;
#ifndef _DEBUG
    try
    {
#endif
        json jo = json::parse(text);
        int code = jo.value("code", -1);                // 本次获取的状态码
        if (code != 0)
        {
            return;
        }
        json data = jo.value("data", json());
        json admin = data.value("admin", json::array());  // 管理员权限
        json room = data.value("room", json::array());    // 普通用户消息
        for (auto& v : admin)
        {
            msgManager.loadMsg(v);
        }
        for (auto& v : room)
        {
            msgManager.loadMsg(v);
        }
#ifndef _DEBUG
    }
    catch (const std::exception&)
    {
        std::cerr << "JSON解析时遇到问题" << "\n";
    }
#endif
}

// 发送请求
static void sendGetRequest(const std::string& roomId)
{
    const std::string url = "https://api.live.bilibili.com/ajax/msg?roomid=" + roomId;
    //const std::string url = "http://qumod.cc";
    CURL* curl;
    CURLcode res;

    std::string readBuffer;

    if (!workingState)
    {
        // 初始化资源
        workingState = true;
        curl_global_init(CURL_GLOBAL_DEFAULT);
    }

    curl = curl_easy_init();
    if (curl)
    {
        // 设置URL
        curl_easy_setopt(curl, CURLOPT_URL, url.c_str());

        // 设置写入回调函数
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, writeCallback);

        // 设置写入回调函数的参数
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, &readBuffer);

        // 执行请求
        res = curl_easy_perform(curl);

        // 检查错误
        if (res != CURLE_OK)
        {
            std::cerr << "HTTPS请求异常: " << curl_easy_strerror(res) << std::endl;
            std::cerr << "URL: " << url << std::endl;
        }
        else
        {
            // std::cout << readBuffer;
            readBarrage(readBuffer);
        }
        // 清理
        curl_easy_cleanup(curl);
    }
}

int main(int argc, char* argv[])
{
#ifdef _DEBUG
    // DEBUG设置环境编码以便调试 MC环境默认编码即UTF8因此不需要处理
    Encoding::initEnvcode();
#endif
    std::string roomId;
    #ifdef _DEBUG
        // DEBUG下使用默认参数调试
        roomId = "407149";
    #else
        if (argc < 2)
        {
            std::cout << "缺少必要参数" << std::endl;
            return 0;
        }
        roomId = argv[1];
    #endif

    int workNow = true;

    while (workNow)
    {
        // 弹幕消息同步间隔
        std::this_thread::sleep_for(std::chrono::seconds(2));
        sendGetRequest(roomId);
    }

    if (workingState)
    {
        workingState = false;
        curl_global_cleanup();
    }
	return 0;
}
